package cn.ctyun.ipush.service.impl;

import cn.ctyun.ipush.event.ToolSpring;
import cn.ctyun.ipush.model.*;
import cn.ctyun.ipush.service.TaskService;
import cn.ctyun.ipush.service.YixinTokenService;
import cn.ctyun.ipush.utils.*;
import cn.ctyun.ipush.vo.ScheduleJobVo;
import cn.ctyun.ipush.vo.TaskVo;
import cn.ctyun.ipush.web.user.bo.UserModel;
import com.aspose.cells.*;
import com.dexcoder.commons.utils.UUIDUtils;
import com.dexcoder.dal.JdbcDao;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: user
 * Date: 16-7-14
 * Time: 下午4:21
 * To change this template use File | Settings | File Templates.
 */
@Service
public class JobService {

    @Autowired
    private TaskService taskService;

    @Autowired
    private JdbcDao jdbcDao;

    /* 日志对象 */
    private static final Logger LOG = LoggerFactory.getLogger(JobService.class);

    public boolean runOnce(String taskId) {
        Long startTime = System.currentTimeMillis();

        TaskVo taskVo = taskService.getTaskVoByTaskId(taskId);
        TaskDetailModel taskDetailModel = taskVo.getTaskDetail();

        ScheduleJobVo scheduleJobVo = new ScheduleJobVo();
        scheduleJobVo.setJobName(taskDetailModel.getTaskName());
        scheduleJobVo.setJobGroup(taskDetailModel.getTaskGroupName());


        LOG.info(String.format("---once JobTask start execute : jobGroup: %s ,jobName: %s,start Time: %s---------- ", taskDetailModel.getTaskGroupName(), taskDetailModel.getTaskName(), DateUtils.timestampToDataString(System.currentTimeMillis())));

        //将数据库数据灌入到Excel模板中，并生成Excel文件
        LOG.info("Excel 文件生成开始");
        ExcelModel excelModel = new ExcelModel();
        WorkbookDesigner workbookDesigner = DataUtils.DBDataToExcelByExcelSql(scheduleJobVo, taskVo, DateUtils.dateToString(new Date()), excelModel, LOG);
        if (null == workbookDesigner) {
            LOG.error("Excel 文件生成失败");
            DataUtils.exceptionDo(taskVo, scheduleJobVo, "Excel 文件生成失败", jdbcDao);
            return false;
        } else {
            LOG.info("Excel 文件生成结束");
        }

        //将Excel文件按指定要求生成照片
        LOG.info("workSheet转换图片开始");
        PictureModel pictureModel = taskVo.getPicture();
        Map<String, String> picAndExcelMap = DataUtils.WorkSheetToPicture(scheduleJobVo, workbookDesigner, pictureModel, LOG);
        picAndExcelMap.put("excel", excelModel.getExcelPath());
        if (null == picAndExcelMap) {
            LOG.error("workSheet转换图片失败");
            DataUtils.exceptionDo(taskVo, scheduleJobVo, "workSheet转换图片失败", jdbcDao);
            return false;
        } else {
            LOG.info("workSheet转换图片完成");
        }

        //发送邮件
        if (taskVo.getIsSendEmail().equals("1")) {
            try {
                LOG.info("邮件发送开始");
                boolean isSend = true;
                String picPathList = picAndExcelMap.get("picture");
                String excelPaht = picAndExcelMap.get("excel");
                EmailModel emailModel = taskVo.getEmail();
                //v1.1
                emailModel.setEmailContent(taskVo.getEmailContent());
                emailModel.setEmailSubject(taskVo.getEmailSubject());
                //v1.1
                if (taskVo.getIsSendExcel().equals("1") && taskVo.getIsSendPicture().equals("1")) {
                    emailModel.setAttachmentList(excelPaht + "$" + picPathList);
                } else if (taskVo.getIsSendExcel().equals("1") && taskVo.getIsSendPicture().equals("0")) {
                    emailModel.setAttachmentList(excelPaht);
                } else if (taskVo.getIsSendExcel().equals("0") && taskVo.getIsSendPicture().equals("1")) {
                    emailModel.setAttachmentList(picPathList);
                } else {
                    isSend = false;
                }
                if (isSend) {
                    if (!EmailUtils.startMailSendTask(emailModel)) {
                        LOG.error("邮件发送失败，请检查邮件参数是否正确");
                    }
                } else {
                    LOG.info("邮件发送内容 设置为 EXCEL和图片都不发送！！！");
                }
                LOG.info("邮件发送结束");
            } catch (Exception e) {
                LOG.error("邮件发送失败，错误消息：" + e.getMessage());
                DataUtils.exceptionDo(taskVo, scheduleJobVo, "邮件发送失败，错误消息：" + e.getMessage(), jdbcDao);
                return false;
            }
        } else {
            LOG.info("邮件设置为 不发送邮件");
        }

        //发送易信
        if (taskVo.getIsSendYixin().equals("1")) {
            List<String> nicks = new ArrayList<String>();
            for (String nick : taskVo.getYixinReceivers().split(",")) {
                nicks.add(nick);
            }
            //nicks.add(nick1);
            List<String> imgs = new ArrayList<String>();
            //String img = "http://e.hiphotos.baidu.com/exp/w=480/sign=b70c5ab516ce36d3a20482380af23a24/7aec54e736d12f2e5581080f4cc2d562843568dd.jpg";
            //String url = "http://e.hiphotos.baidu.com/exp/w=480/sign=b70c5ab516ce36d3a20482380af23a24/7aec54e736d12f2e5581080f4cc2d562843568dd.jpg";
            //imgs.add(img);
            String title = "IPUSH推送图片";
            LOG.info("易信开始发送");
            for (String picYixinUrl : picAndExcelMap.get("pictureYixinURL").split("\\$")) {
                imgs.add(picYixinUrl);
            }
            DataUtils.sendYixinToFriends(nicks, imgs, imgs, title, LOG);
            LOG.info("易信结束发送");
        } else {
            LOG.info("易信设置为 不进行易信发送！！！");
        }

        long endTime = System.currentTimeMillis();
        LOG.info(String.format("---once JobTask end execute : jobGroup: %s ,jobName: %s,cost time: %s msec---------- ", taskDetailModel.getTaskGroupName(), taskDetailModel.getTaskName(), endTime - startTime));
        return true;
    }
}
